
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList, get_string_to_date
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...service.common import insert_data, get_current_user_id, find_data, update_data, delete_data, get_condition, get_info, get_current_organization_id
from ...service.buss_pub.bill_manage import BillManageService, TypeId, OperationType
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date


class DemandService(MongoService):
    '''需求'''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_demand(self, condition, page, count):
        '''
            获取需求列表
            Arguments:
                condition   {dict}      条件
                page        {number}    页码
                count       {number}    条数
        '''
        keys = ['id', 'publisher_id', 'elder_id', 'demand_title']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('publisher_id') == values['publisher_id'])
                           & (C('demand_title').like(values['demand_title']))
                           & (C('elder_id') == values['elder_id']))
        if 'sort' in condition and condition['sort'] != None:
            if condition['sort'] == '时间':
                _filter.sort({'create_date': -1})
            elif condition['sort'] == '价格':
                _filter.sort({'price': -1})
        _filter.project({'_id': 0, })
        res = self.page_query(_filter, 'PT_Demand', page, count)
        return res

    def get_demand_details(self, condition, page, count):
        '''
            获取需求详情
            Arguments:
                condition   {dict}      条件
                page        {number}    页码
                count       {number}    条数
        '''
        keys = ['id', 'publisher_id', 'elder_id', 'demand_title']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('publisher_id') == values['publisher_id'])
                           & (C('demand_title').like(values['demand_title']))
                           & (C('elder_id') == values['elder_id']))\
            .lookup_bill('PT_User', 'emergency_contact_id', 'id', 'emergency_contact')\
            .lookup_bill('PT_Service_Type', 'service_type', 'id', 'service_type')\
            .lookup_bill('PT_Demand_Bidding', 'id', 'demand_id', 'bidding_servicer')\
            .lookup_bill('PT_User', 'bidding_servicer.bidders_organization_id', 'id', 'bidding_organization')\
            .project({'_id': 0, 'emergency_contact._id': 0, 'service_type._id': 0, 'bidding_servicer._id': 0, 'bidding_organization._id': 0})\
            .sort({'modify_date': -1})
        res = self.page_query(_filter, 'PT_Demand', page, count)
        return res

    def update_demand(self, demand):
        '''新增/编辑需求

        Arguments:
            demand   {dict}      条件
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            publisher_id = get_current_user_id(self.session)
            data = get_info({**demand}, self.session)
            data['publisher_id'] = publisher_id
            data['state'] = '等待接单'
            data['price'] = int(data['price'])
            if 'id' in demand.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.demand.value, data, 'PT_Demand')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.demand.value, data, 'PT_Demand')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def update_demand_bidding(self, bidding):
        '''新增/编辑需求竞单

        Arguments:
            demand   {dict}      条件
        '''
        res = 'fail'
        user_id = get_current_user_id(self.session)
        bidders_organization_id = get_current_organization_id(self.session)
        # 竞单者id
        bidding['bidders'] = user_id
        # 竞单组织机构id
        bidding['bidders_organization_id'] = bidders_organization_id

        def process_func(db):
            nonlocal res
            data = get_info({**bidding}, self.session)

            if 'id' in bidding.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.bidding.value, data, 'PT_Demand_Bidding')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.bidding.value, data, 'PT_Demand_Bidding')
                if bill_id:
                    res = 'Success'
            # 竞单成功的话要修改发布的需求的竞单服务商
            if res == 'Success':
                _filter = MongoBillFilter()
                print(bidding)
                _filter.match_bill((C('id') == bidding['demand_id']))\
                    .project({'_id': 0})
                datas = self.page_query(_filter, 'PT_Demand', 1, 1)
                demand = datas['result'][0]
                demand['state'] = '有人竞单'
                demand['bidders_organization_id'] = bidding['bidders_organization_id']
                yes_or_no = self.bill_manage_service.add_bill(OperationType.update.value,
                                                              TypeId.demand.value, demand, 'PT_Demand')
                if yes_or_no:
                    res = 'Success'
                else:
                    res = '添加需求竞单服务商失败'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def cancel_demand(self, bidding):
        '''取消需求

        Arguments:
            demand   {dict}      条件
        '''
        res = 'fail'
        bidding['state'] = '取消需求'

        def process_func(db):
            nonlocal res

            bill_id = self.bill_manage_service.add_bill(OperationType.delete.value,
                                                        TypeId.demand.value, bidding, 'PT_Demand')
            if bill_id:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
